package com.acegear.horizon.domain.repository;

import com.acegear.horizon.domain.models.Daily;
import com.acegear.horizon.domain.repository.jpa.AGDailyFeedRepository;
import com.acegear.horizon.domain.repository.jpa.AGDailyRepository;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import java.util.Optional;
import java.util.stream.Stream;

/**
 * Created by wangsike on 2016/12/22.
 */
@Component
public class DailyRepository {

    @Autowired
    private AGDailyRepository agDailyRepository;

    @Autowired
    private AGDailyFeedRepository agDailyFeedRepository;

    public Optional<Daily> findByDailyId(Long dailyId) {
        return agDailyRepository.findTopByDailyId(dailyId).map(Daily::new);
    }

    public Optional<Daily> current() {
        return agDailyRepository
                .findTopByOrderByDateDesc()
                .map(Daily::new);
    }

    public Optional<Daily> previous(Long dailyId) {
        return agDailyRepository
                .findTopByDailyId(dailyId)
                .flatMap(daily -> agDailyRepository.findTopByDateLessThanOrderByDateDesc(daily.getDate()))
                .map(Daily::new);
    }

    public Optional<Daily> next(Long dailyId) {
        return agDailyRepository
                .findTopByDailyId(dailyId)
                .flatMap(daily -> agDailyRepository.findTopByDateGreaterThanOrderByDateAsc(daily.getDate()))
                .map(Daily::new);
    }

    public Stream<Daily> find(Pageable pageable) {
        return agDailyRepository.findByOrderByDateDesc(pageable)
                .stream()
                .map(Daily::new);
    }
}
